package com.maben.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 用户controller
 */
@RestController
@RequestMapping("user")
@ApiOperation("用户控制类")
public class UserController {
    /**
     * 转向登录页
     */
    @ApiOperation("转向登录页")
    @GetMapping("/go2index")
    public ModelAndView go2index() {
        // 判断是否登录
        if (StpUtil.isLogin()) {
            // 已登录跳转到首页
            return new ModelAndView("redirect:/home");
        }
        return new ModelAndView("index.html");
    }

    /**
     * 登录接口
     */
    @ApiOperation("用户登录接口")
    @PostMapping("doLogin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true, paramType = "query", dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query", dataTypeClass = String.class),
    })
    public SaResult doLogin(String username, String password) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        if ("maben".equals(username) && "123456".equals(password)) {
            StpUtil.login(1001);
            return SaResult.data(StpUtil.getTokenInfo());
        }
        return SaResult.error("登录失败");
    }

    /**
     * 登出接口
     */
    @ApiOperation("用户退出接口")
    @PostMapping("doLogout")
    public SaResult doLogout() {
        if (StpUtil.isLogin()) {
            StpUtil.logout();
        }
        return SaResult.ok("退出成功");
    }
}
